package demo.huodongbaoming.service.impl;

import demo.huodongbaoming.dto.ResponseResult;
import demo.huodongbaoming.service.RemoteDemoService;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class RemoteDemoServiceImpl implements RemoteDemoService {
    private static final Logger logger = LoggerFactory.getLogger(RemoteDemoServiceImpl.class);

    @Override
    @CircuitBreaker(name = "demo-circuit-breaker", fallbackMethod = "fallback")
    public ResponseResult<String> callRemoteService(boolean fail) {
        logger.info("[熔断测试] 开始调用 callRemoteService, fail={} ...", fail);
        if (fail) {
            logger.error("[熔断测试] 远程服务调用失败，抛出异常，触发熔断");
            throw new RuntimeException("远程服务调用失败，触发熔断");
        }
        logger.info("[熔断测试] 远程服务调用成功，返回正常数据");
        return ResponseResult.success("远程服务调用成功", "远程服务返回数据");
    }

    // 熔断降级方法，参数需与原方法一致，最后加 Throwable
    public ResponseResult<String> fallback(boolean fail, Throwable t) {
        logger.warn("[熔断测试] 进入降级方法 fallback，fail={}, 原因：{}", fail, t.getMessage());
        return ResponseResult.fail(500, "服务降级：远程服务不可用（熔断），原因：" + t.getMessage());
    }
} 